/*
 * TagsFromFileName.java
 *
 * Created on 3 maggio 2007, 10.22
 */

package alecava;

import alecava.interfacce.Progressable;
import java.util.Vector;
import javax.swing.JOptionPane;
import java.io.*;

/**
 *
 * @author  alecava
 */
public class TagsFromFileName extends javax.swing.JFrame implements Progressable {
    
    private Vector<AbstractCavaID3> v;
    private final String lastEspr = "espressioneEstrai";
    /** Creates new form TagsFromFileName */
    public TagsFromFileName(Vector<AbstractCavaID3> v) {
        initComponents();
        this.setVisible(true);
        progress.setStringPainted(true);
        this.v = v;
        lista.setListData(v);
        /*imposta le info*/
        textInfo.setContentType("text/html");
        textInfo.setText("<html><font size=\"3\">E' possibile definire delle espressioni che permettono una estrazione automatica dei tag dal nome del file." +
                "<br/>Gli operatori concessi sono <b>\"artista\"</b>, <b>\"titolo\"</b>, <b>\"album\"</b>, <b>\"commento\"</b>, <b>\"traccia\"</b>, <b>\"anno\"</b>, <b>\"genere\"</b>." +
                "<br/><i>Esempio: \"traccia\" - \"artista\" - \"titolo\"</i>" +
                "<br/><i>Nota: è necessario che i campi contenenti i diversi tag siano separati da caratteri non alfanumerici come -, _ o /</i></font></html>");
        /*ricarica l'espressione se esiste*/
        textEspressione.setText((String) MemoryCard.carica(lastEspr));
        //aggiorna l'anteprima
        this.aggiornaAnteprima();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        popMenuDel = new javax.swing.JPopupMenu();
        popItemDel = new javax.swing.JMenuItem();
        jLabel1 = new javax.swing.JLabel();
        textEspressione = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        lista = new javax.swing.JList();
        btnEstrai = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textInfo = new javax.swing.JTextPane();
        progress = new javax.swing.JProgressBar();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        labelArtista = new javax.swing.JLabel();
        labelTitolo = new javax.swing.JLabel();
        labelAlbum = new javax.swing.JLabel();
        labelCommento = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        labelTraccia = new javax.swing.JLabel();
        labelAnno = new javax.swing.JLabel();
        labelGenere = new javax.swing.JLabel();
        labelErrore = new javax.swing.JLabel();

        popItemDel.setText("Rimuovi");
        popItemDel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                popItemDelActionPerformed(evt);
            }
        });
        popMenuDel.add(popItemDel);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Estrai tag da nome del file");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel1.setText("Espressione:");

        textEspressione.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                textEspressioneKeyTyped(evt);
            }
        });

        lista.setComponentPopupMenu(popMenuDel);
        lista.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lista);

        btnEstrai.setText("Scrivi tags");
        btnEstrai.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEstraiMouseClicked(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Dialog", 0, 12));
        jLabel2.setText("Files da processare:");

        textInfo.setBackground(new java.awt.Color(204, 255, 204));
        jScrollPane2.setViewportView(textInfo);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Anteprima"));

        jLabel3.setText("Artista:");

        jLabel4.setText("Titolo:");

        jLabel5.setText("Album:");

        jLabel6.setText("Commento:");

        labelArtista.setFont(new java.awt.Font("Dialog", 0, 12));

        labelTitolo.setFont(new java.awt.Font("Dialog", 0, 12));

        labelAlbum.setFont(new java.awt.Font("Dialog", 0, 12));

        labelCommento.setFont(new java.awt.Font("Dialog", 0, 12));

        jLabel11.setText("Anno:");

        jLabel12.setText("Genere:");

        jLabel13.setText("Traccia:");

        labelTraccia.setFont(new java.awt.Font("Dialog", 0, 12));

        labelAnno.setFont(new java.awt.Font("Dialog", 0, 12));

        labelGenere.setFont(new java.awt.Font("Dialog", 0, 12));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(labelArtista))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(labelTitolo))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(labelAlbum)))
                        .addGap(107, 107, 107)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel11)
                            .addComponent(jLabel12)
                            .addComponent(jLabel13))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelAnno)
                            .addComponent(labelGenere)
                            .addComponent(labelTraccia)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelCommento)))
                .addContainerGap(348, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(labelArtista))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(labelTitolo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(labelAlbum))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(labelCommento)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel11)
                            .addComponent(labelAnno))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel12)
                            .addComponent(labelGenere))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel13)
                            .addComponent(labelTraccia))))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .addComponent(textEspressione, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelErrore)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 482, Short.MAX_VALUE)
                        .addComponent(btnEstrai))
                    .addComponent(progress, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textEspressione, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEstrai)
                    .addComponent(labelErrore))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void popItemDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_popItemDelActionPerformed
    // TODO add your handling code here:
    if (lista.getSelectedIndices().length > 0) {
        int[] indices = lista.getSelectedIndices();
        Vector<AbstractCavaID3> mp3s = new Vector<AbstractCavaID3>();
        for (int i = 0; i < lista.getModel().getSize(); i++) {
            mp3s.add((AbstractCavaID3) lista.getModel().getElementAt(i));
        }
        for (int i = indices.length - 1; i >= 0; i--) {
            mp3s.remove(indices[i]);
            v.remove(indices[i]);
        }
        lista.setListData(mp3s);
    }
}//GEN-LAST:event_popItemDelActionPerformed
    
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
        MemoryCard.salva(lastEspr, textEspressione.getText());
    }//GEN-LAST:event_formWindowClosing
    
    private void listaValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaValueChanged
// TODO add your handling code here:
        this.aggiornaAnteprima();
    }//GEN-LAST:event_listaValueChanged
    
    private void textEspressioneKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textEspressioneKeyTyped
// TODO add your handling code here:
        this.aggiornaAnteprima();
    }//GEN-LAST:event_textEspressioneKeyTyped
    
    private void btnEstraiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEstraiMouseClicked
// TODO add your handling code here:
        if (!textEspressione.getText().equals("")){
            ID3FileNameHandler handler = new ID3FileNameHandler();
            String[][] fields = new String[v.size()][7];
            String[] temp;
            AbstractCavaID3[] mp3 = new AbstractCavaID3[v.size()];
            int index = 0;
            /*processa ogni file*/
            try {
                for (AbstractCavaID3 id : v){
                    //prende l'mp3 da processare
                    mp3[index] = id;
                    //estrae i tag da scrivere
                    temp = handler.extractTagFromFileName(textEspressione.getText(), id);
                    //riempe i campi da scrivere
                    for (int i = 0; i < 7; i++)
                        fields[index][i] = temp[i];
                    //incrementa
                    index++;
                }
                //lancio il thread per la scrittura
                Thread t = new MassWriter(mp3, fields, this);
                t.start();
            } catch (SintassiErrataException ex) {
                JOptionPane.showMessageDialog(this,"Sintassi dell'espressione errata", "Errore sintassi", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this,"Devi inserire un'espressione", "Errore", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnEstraiMouseClicked
    
    private void aggiornaAnteprima(){
        ID3FileNameHandler handler = new ID3FileNameHandler();
        AbstractCavaID3 i;
        if (lista.getSelectedIndex() != -1)
            i = (AbstractCavaID3) lista.getSelectedValue();
        else
            i = (AbstractCavaID3) lista.getModel().getElementAt(0);
        
        try {
            String[] ante = handler.extractTagFromFileName(textEspressione.getText(), i);
            //imposta le label
            labelArtista.setText(ante[0]);
            labelTitolo.setText(ante[1]);
            labelAlbum.setText(ante[2]);
            labelCommento.setText(ante[3]);
            labelAnno.setText(ante[4]);
            labelGenere.setText(ante[5]);
            labelTraccia.setText(ante[6]);
            //azzera eventuli messaggi di errore
            labelErrore.setText("");
        } catch (SintassiErrataException ex) {
            labelErrore.setText(ex.getMessage());
        }
    }
    
    public void start() {
        progress.setValue(0);
    }
    
    public void finish() {
        //progress.setValue(0);
    }
    
    public void setMax(int x) {
        progress.setMinimum(0);
        progress.setMaximum(x-1);
    }
    
    public void setPosition(int x) {
        progress.setValue(x);
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEstrai;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelAlbum;
    private javax.swing.JLabel labelAnno;
    private javax.swing.JLabel labelArtista;
    private javax.swing.JLabel labelCommento;
    private javax.swing.JLabel labelErrore;
    private javax.swing.JLabel labelGenere;
    private javax.swing.JLabel labelTitolo;
    private javax.swing.JLabel labelTraccia;
    private javax.swing.JList lista;
    private javax.swing.JMenuItem popItemDel;
    private javax.swing.JPopupMenu popMenuDel;
    private javax.swing.JProgressBar progress;
    private javax.swing.JTextField textEspressione;
    private javax.swing.JTextPane textInfo;
    // End of variables declaration//GEN-END:variables
    
}
